home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9213 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.3 KB  |  55 lines

  1. Newsgroups: comp.lang.c++
  2. Path: netcom.com!marnold
  3. From: marnold@netcom.com (Matt Arnold)
  4. Subject: Re: how slow are virtual functions?
  5. Message-ID: <marnoldDnJ15M.IDF@netcom.com>
  6. Organization: NETCOM On-line Communication Services (408 261-4700 guest)
  7. References: <4gioqc$9f0@onlink3.onlink.net>
  8. Date: Thu, 29 Feb 1996 07:36:57 GMT
  9. Sender: marnold@netcom23.netcom.com
  10.  
  11. wfss16@onlink.net writes:
  12.  
  13. >Can anyone give me some timings/good anology as to how much slower calling a virtual
  14. >function is as to a normal one?
  15.  
  16. A virtual fucntion call is basically equivalent to a call through function
  17. pointer in C (or C++!).  When you declare virtual functions, you cause the
  18. compiler to arrange for a table of function-pointers.  Depending on which
  19. class an object is, it uses a slightly different version of the table.  This 
  20. table is commonly known as the "virtual table" or "vtbl" and most of the cost 
  21. of arranging for it all is paid at compile-time.  As I said, the only cost at 
  22. run-time is basically the cost of an indirect function call.
  23.  
  24.    PFUNC pfunc = &SomeFunc;  
  25.  
  26.    // when you compare "normal" functions to virtual functions, you
  27.    // are basically comparing...
  28.  
  29.    SomeFunc(123);   // ...this (a normal call)
  30.  
  31.    pfunc(123);      // ...with this (an indirect call)
  32.  
  33.  
  34. If you think about it, if you wanted to implement virtual function-esque
  35. behavior yourself, what would you use?  Tables of function pointers, of 
  36. course.   Depending on some condition, you'd change the function addresses
  37. contained in the table.  This is what a C++ compiler does for you.
  38.  
  39. Virtual functions aren't some magically expensive thing.  They are just
  40. indirect function calls.
  41.  
  42. If you want to exactly how your compiler implements virtual function 
  43. calls, look at some assembly output sometime.  It can be most revealing.
  44.  
  45. Regards,
  46. -------------------------------------------------------------------------
  47. Matt Arnold                       |        | ||| | |||| |  | | || ||
  48. marnold@netcom.com                |        | ||| | |||| |  | | || ||
  49. Boston, MA                        |      0 | ||| | |||| |  | | || ||
  50. 617.389.7384 (h) 617.576.2760 (w) |        | ||| | |||| |  | | || ||
  51. C++, MIDI, Win32/95 developer     |        | ||| 4 3 1   0 8 3 || ||
  52. -------------------------------------------------------------------------
  53.  
  54.  
  55.